package cn.edu.ncu.housinghub.interceptor;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.exception.BusinessException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Set;

@Component
public class IdentityVerificationInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 定义需要拦截的URL模式
        String requestURI = request.getRequestURI();

        // 判断是否需要进行实名认证校验
        if (needVerification(requestURI)) {
            // 2. 获取请求头中的token
            String token = request.getHeader("info");

            // 3. 验证token是否存在
            if (token == null || token.trim().isEmpty()) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_MISSING);
            }

            // 4. 从Redis中查询token对应的用户信息
            Set<String> keys = redisTemplate.keys(SystemConstant.REDIS_TOKEN_PREFIX_USER.getStringValue() + "*:" + token);
            if ( keys.isEmpty()) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }

            // 5. 获取用户信息
            String redisKey = keys.iterator().next();
            User loginUser = (User) redisTemplate.opsForValue().get(redisKey);
            if (loginUser == null) {
                throw new BusinessException(ErrorCodeConstant.TOKEN_INVALID);
            }

            // 6. 验证用户是否已实名认证
            if (!loginUser.getIsIdentityVerified()) {
                throw new BusinessException(ErrorCodeConstant.USER_DONT_VERIFIED);
            }
        }

        // 验证通过，继续处理请求
        return true;
    }

    /**
     * 判断当前请求是否需要进行实名认证校验
     */
    private boolean needVerification(String requestURI) {
        // 这里可以根据实际业务需求配置需要拦截的子URL模式
        return requestURI.startsWith("/landlord/");
    }



}
